﻿Imports System.Windows.Forms.VisualStyles
Imports Business
Imports SAT.FrmManagerFPTerminal
Imports System.Data
Imports System.Data.SqlClient
Imports System.Threading

Public Class frmMain

    Public Shared serverName As String
    'Public Property ServerNameProperty() As String
    '    Get
    '        Return serverName
    '    End Get
    '    Set(ByVal value As String)
    '        serverName = value
    '    End Set
    'End Property

    Public Sub New()

        Dim frmLogin As New frmLogin
        frmLogin.ShowDialog()

        ' This call is required by the designer.
        InitializeComponent()
        ' Add any initialization after the InitializeComponent() call.
      

    End Sub

#Region "Customize tabpage"


    Private Sub TabControl1_DrawItem(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DrawItemEventArgs) Handles tabControl.DrawItem
        Dim closefont As Font = New Font(e.Font.FontFamily, e.Font.Size, FontStyle.Regular)
        Dim titlefont As Font

        ' Get tab size as rectangle
        Dim tabRect As Rectangle = tabControl.GetTabRect(e.Index)

        ' ve background cho tab 
        If e.State = DrawItemState.Selected Then
            e.Graphics.FillRectangle(Brushes.White, tabRect)
            titlefont = New Font(e.Font.FontFamily, e.Font.Size, FontStyle.Bold)
            e.DrawFocusRectangle()
        Else
            e.Graphics.FillRectangle(Brushes.Transparent, tabRect)
            titlefont = New Font(e.Font.FontFamily, e.Font.Size, FontStyle.Regular)
        End If
        e.Graphics.DrawString("x", closefont, Brushes.Gray, e.Bounds.Right - 13, e.Bounds.Top + 4)
        e.Graphics.DrawString(tabControl.TabPages(e.Index).Text, titlefont, Brushes.Black, e.Bounds.Left + 5, e.Bounds.Top + 5)
    End Sub

    Private Sub TabControl1_MouseDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles tabControl.MouseDown

        For i As Integer = 0 To tabControl.TabPages.Count - 1

            Dim rPage As Rectangle = tabControl.GetTabRect(i)

            Dim closeButton As Rectangle = New Rectangle(rPage.Right - 13, rPage.Top + 4, 10, 10)

            If closeButton.Contains(e.Location) Then

                If Not tabControl.TabPages.Item(i).Name.Equals("tabHome") Then
                    ' show message box confirm
                    tabControl.TabPages.RemoveAt(i)
                    Exit For

                End If

            Else

                GoTo ContinueLoop

            End If

ContinueLoop: Next

    End Sub

#End Region

#Region "Functions"

    ''' <summary>
    ''' Check tabpage if it's existed
    ''' </summary>
    ''' <param name="tabname"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Function CheckExistedTab(ByVal tabname As String) As Integer

        Dim i As Integer
        For i = 0 To tabControl.TabCount - 1 Step 1
            If tabControl.TabPages.Item(i).Name.Equals(tabname) Then
                Return i
            End If
        Next
        Return -1
    End Function

    ''' <summary>
    ''' Add tabpage to tabControl
    ''' </summary>
    ''' <param name="form">Form</param>
    ''' <param name="title"></param>
    ''' <param name="name"></param>
    ''' <remarks></remarks>
    Public Sub AddTabpage(ByVal form As Windows.Forms.Form, ByVal title As String, ByVal name As String)
        tabControl.Visible = True

        'check tabpage existed
        If CheckExistedTab(name) > -1 Then
            tabControl.SelectedTab = tabControl.TabPages(CheckExistedTab(name))
        Else

            Dim tabpage As TabPage = New TabPage(title)
            tabControl.TabPages.Add(tabpage)
            tabpage.Name = name
            form.FormBorderStyle = FormBorderStyle.None
            form.TopLevel = False
            form.Dock = DockStyle.Fill
            form.Parent = tabpage
            tabpage.Controls.Add(form)
            form.Show()
            tabControl.SelectedTab = tabpage
        End If
    End Sub

    ''' <summary>
    ''' Remove tabpage in tavControl
    ''' </summary>
    ''' <remarks></remarks>
    Public Sub RemoveTabpage()
        tabControl.TabPages.Remove(tabControl.SelectedTab)
    End Sub

#End Region

#Region "Event"

    Private Sub mnuFPTer_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuFPTer.Click

        Dim frmManagerFpTerminal As FrmManagerFPTerminal = New FrmManagerFPTerminal(serverName)

        AddTabpage(frmManagerFpTerminal, "Manage FP Terminal", "tabMFPT")

    End Sub


    Private Sub mnuMonthly_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuMonthly.Click

        Dim frmMonthly As frmMonthly = New frmMonthly(serverName)

        AddTabpage(frmMonthly, "Manage Monthly Canlendar", "tabMonthly")

    End Sub

    Private Sub mnuAttendance_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuAttendance.Click

        Dim frmAttendance As frmAttendance = New frmAttendance(serverName)

        AddTabpage(frmAttendance, "Attendance Data", "tabAtData")

    End Sub

    Private Sub mnuFPData_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuFPData.Click

        Dim frmLoginFingerKeeper As frmLoginFingerKeeper = New frmLoginFingerKeeper(serverName)

        frmLoginFingerKeeper.ShowDialog()

    End Sub

    Private Sub mnuExit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuExit.Click

        If MessageBox.Show("Do you want to exit program?", "Message", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = DialogResult.Yes Then

            Application.Exit()

        End If

    End Sub

    Private Sub mnuEmployee_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuEmployee.Click

        Dim frmListEmployee As frmListEmployee = New frmListEmployee(serverName)

        AddTabpage(frmListEmployee, "Manage Employee", "tabManageEm")

    End Sub

#End Region



    Private Sub mnuHoliday_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuHoliday.Click

        Dim frmHoliday As frmHoliday = New frmHoliday(serverName)

        AddTabpage(frmHoliday, "Manage Holiday", "tabManageHoliday")

    End Sub

    Private Sub mnuCompany_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuOrUnit.Click

        Dim frmCompanyDepartment As frmCompanyDepartment = New frmCompanyDepartment(serverName)

        AddTabpage(frmCompanyDepartment, "Manage Organizational Unit", "tabCompanyDepartment")

    End Sub


    Private Sub mnuTimetable_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuTimetable.Click


        Dim frmTimetable As frmTimetable = New frmTimetable(serverName)

        AddTabpage(frmTimetable, "Manage Timetable", "tabManageTimetable")

    End Sub


    'abcxyz backup
    Private myCnn As Data.SqlClient.SqlConnection
    Private Cmd As Data.SqlClient.SqlCommand
    Private da As Data.SqlClient.SqlDataAdapter
    Private Sub Connect() 'Thủ tục kết nối dữ liệu
        Try
            myCnn = New SqlConnection(serverName)
            myCnn.Open()
            If myCnn.State <> ConnectionState.Open Then
                'Nếu kết nối bị lỗi thì thông báo cho người dùng biết
                MsgBox("Cannot connect to the Server, please check it!", MsgBoxStyle.Critical, "Error")
            End If
        Catch ex As Exception
            'Nếu có lỗi thì báo lỗi
            MsgBox("Cannot connect to the Server, please check it!", MsgBoxStyle.Critical, "Error")
            End
        End Try

    End Sub

    Public Sub close_Cnn()
        'Đóng kết nối đến CSDL
        If myCnn.State = ConnectionState.Open Then
            myCnn.Close()
            myCnn.Dispose()
        End If
    End Sub

    Public Sub Create_Cmd(ByVal strSQL As String)
        'Tạo Command để lấy dữ liệu
        Cmd = myCnn.CreateCommand
        Cmd.CommandText = strSQL
        Cmd.ExecuteNonQuery()
    End Sub



    Private Sub mnuBackup_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuBackup.Click
        Dim strPath As String
        Dim objSaveFileDialog As New SaveFileDialog
        Application.DoEvents()
        'Set the Save dialog properties
        With objSaveFileDialog
            .FileName = "backupdata1"
            .Filter = "Text files (*.bak)|*.bak|All files (*.*)|*.*"
            .FilterIndex = 1
            .OverwritePrompt = True
            .Title = "Save File Dialog"
            .InitialDirectory = Application.StartupPath
        End With

        'Show the Save dialog and if the user clicks the Save button,
        'save the file
        If objSaveFileDialog.ShowDialog = Windows.Forms.DialogResult.OK Then
            strPath = objSaveFileDialog.FileName
            'MsgBox(strPath)
            Try
                Connect()
                'MsgBox("BACKUP DATABASE TIMEKEEPER TO DISK = " & strPath)
                Create_Cmd("BACKUP DATABASE TIMEKEEPER TO DISK = '" & strPath & "'")
                close_Cnn()
                MsgBox("Backup is succeed!")
            Catch ex As Exception
                MsgBox(ex.Message, MsgBoxStyle.Critical, "Error")
                End
            End Try
        End If



    End Sub

    Private Sub mnuRestore_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuRestore.Click
        Dim strPath As String
        Dim myFileDialog As OpenFileDialog = New OpenFileDialog()
        With myFileDialog
            .Filter = "BAK Files (*.bak)|*.bak|All Files (*.*)|*.*"
            .FilterIndex = 1
            .InitialDirectory = Application.StartupPath
            .Title = "Open File"
            .CheckFileExists = False
        End With

        If myFileDialog.ShowDialog() = DialogResult.OK Then
            'Console.WriteLine(myFileDialog.FileName)
            strPath = myFileDialog.FileName
            Try
                Connect()
                'MsgBox("RESTORE DATABASE TIMEKEEPER FROM DISK = '" & strPath & "' WITH  FILE = 1,  NOUNLOAD,  STATS = 10")
                Create_Cmd("USE MASTER ALTER DATABASE TIMEKEEPER SET Single_User WITH Rollback Immediate ALTER DATABASE TIMEKEEPER SET Multi_User RESTORE DATABASE TIMEKEEPER FROM DISK = '" & strPath & "' WITH REPLACE")
                close_Cnn()
                MsgBox("Restore is succeed!")
            Catch ex As Exception
                MsgBox(ex.Message, MsgBoxStyle.Critical, "Error")
                End
            End Try
        End If


    End Sub

    Private Sub mnuLogout_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuLogout.Click
        Dim frmLogin As New frmLogin
        frmLogin.ShowDialog()
    End Sub

    Private Sub mnuRecover_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuRecover.Click

        If MessageBox.Show("Are you sure to override all the user data in the FingerPrint with the employee in the database? ", "", MessageBoxButtons.OKCancel, MessageBoxIcon.Asterisk) = DialogResult.OK Then
            Dim gnCommHandleIndex As Long

            'Lay ra cac may cham cong trong mang
            Dim bsTerminalSetting As New BSTerminalSetting(serverName)
            Dim dtTerminalSetting As New DataTable
            dtTerminalSetting = bsTerminalSetting.GetAllTerminalSetting()

            'Lay ra du lieu user terminal data
            Dim bsTerminalUserData As New BSTerminalUserData(serverName)
            Dim dtTerminalUserData As New DataTable
            dtTerminalUserData = bsTerminalUserData.GetAllTerminalUserData()

            'Tao doi tuong tu lop BSFKAttend
            Dim bsFKAttend As New BSFKAttend(serverName)

            'Quet tung may va day du lieu vao
            Try

                For i As Integer = 0 To dtTerminalSetting.Rows.Count - 1

                    'Ket noi de lay gnCommHandleIndex
                    If dtTerminalSetting.Rows.Item(i).Item(3) = DEVICE_TCPIP Then
                        gnCommHandleIndex = bsFKAttend.CheckConnectNet(CInt(dtTerminalSetting.Rows.Item(i).Item(0)),
                                                                       dtTerminalSetting.Rows.Item(i).Item(4),
                                                                       CInt(dtTerminalSetting.Rows.Item(i).Item(5)),
                                                                       5005, False, 2, 1261)
                    Else
                        gnCommHandleIndex = bsFKAttend.CheckConnectUSB(CInt(dtTerminalSetting.Rows.Item(i).Item(0)), 1261)
                    End If

                    'Xoa het du lieu cu trong may FingerPrint
                    bsFKAttend.EmptyEnrollData(gnCommHandleIndex)

                    'Put du lieu tu bang terminal user data vao may FingerPrint
                    For j As Integer = 0 To dtTerminalUserData.Rows.Count - 1
                        FK_PutEnrollDataWithString(gnCommHandleIndex, dtTerminalUserData.Rows.Item(j).Item(0),
                                                   dtTerminalUserData.Rows.Item(j).Item(1),
                                                   dtTerminalUserData.Rows.Item(j).Item(2),
                                                   dtTerminalUserData.Rows.Item(j).Item(3))
                        Application.DoEvents()
                        Me.Text = ("SAT - Recovering Eroll Number " & dtTerminalUserData.Rows.Item(j).Item(0) & " - " & dtTerminalUserData.Rows.Item(j).Item(1))

                    Next

                    'Ghi xong thi dong ket noi
                    bsFKAttend.Disconnect(gnCommHandleIndex)

                Next

                MsgBox("Recover data is succeed!")
                Application.DoEvents()
                Me.Text = "SAT"

            Catch ex As Exception
                MsgBox(ex.Message)
            End Try

            'MsgBox("aaa")
        End If
    End Sub

    Private Sub frmMain_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        Dim home As Form = New Form()

        home.BackgroundImage = Me.BackgroundImage

        home.BackgroundImageLayout = ImageLayout.Stretch

        AddTabpage(home, "Home", "tabHome")
     

    End Sub

    ''' <summary>
    ''' Select the last tab in tabpage 
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub tabControl_ControlRemoved(ByVal sender As System.Object, ByVal e As System.Windows.Forms.ControlEventArgs) Handles tabControl.ControlRemoved

        tabControl.SelectedTab = tabControl.TabPages.Item(tabControl.TabPages.Count - 2)

    End Sub

End Class